package com.gopay.common.asynexport.util;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class BytesUtil {
	
	private static final Logger logger = Logger.getLogger(BytesUtil.class);
	
	 /**
    * 将Excel文件转化成byte数组
    * 
    * @return
    * @throws Exception
    */
   public static byte[] convertExcelToBytes(SXSSFWorkbook excel) throws Exception {
       byte[] excelBytes = null;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       try {
           excel.write(baos);
           baos.flush();
           excelBytes = baos.toByteArray();
           baos.close();
       } catch (IOException e) {
           logger.info("生成Excel文件发生IO异常！");
           throw new RuntimeException("生成Excel文件发生IO异常！请联系管理员");
       }
       try {
           excel.dispose();
       } catch (Exception e) {
           logger.error("清理临时文件异常",e);
       }
       return excelBytes;
   }
   
   /**
    * 构建一个zip Entry
    * 
    * @param zipStream
    * @param data
    * @param fileName
    * @throws Exception
    */
   public static void buildZipEntry(ZipOutputStream zipStream, byte[] data, String fileName) throws Exception {
       ZipEntry excelEntry = new ZipEntry(fileName);
       excelEntry.setSize(data.length);
       try {
           zipStream.putNextEntry(excelEntry);
           zipStream.write(data);
           zipStream.closeEntry();
       } catch (IOException e) {
           logger.info("构建zip Entry发生错误");
           throw new RuntimeException("构建zip Entry发生错误，请联系管理员！");
       }
   }

}
